import * as fs from "fs";
import * as path from "path";
import * as XLSX from "xlsx";
import config from "./config";
import log from "./logger";
import {NodeCO, TrainAllCO} from "./interface"
import sender from "./sender";

const begin = 5;

// 遍历文件夹
function fromDir(startPath: string, callback: Function) {
    if (!fs.existsSync(startPath)) {
        log.info("No directory", startPath);
        return;
    }
    let files = fs.readdirSync(startPath);
    for (let i = 0; i < files.length; i++) {
        let filename = path.join(startPath, files[i]);
        let stat = fs.lstatSync(filename);

        if (stat.isDirectory()) {
            // log.info("isDirectory:", filename)
            fromDir(filename, callback); // 递归遍历文件夹
        } else {
            callback(filename);
        }
    }
}

function readExcelFile(fileName: string) {
    // 读取文件
    const workbook = XLSX.readFile(fileName);
    // 获取第一个工作表名称
    const sheetName = workbook.SheetNames[0];
    // 获取工作表数据
    const worksheet = workbook.Sheets[sheetName];
    // 将工作表数据转换为JSON
    return XLSX.utils.sheet_to_json(worksheet);
}

// 获取最新的10个文件
function getLatestFiles(startPath: string) {
    let filelist: any = [];
    // log.info("filelist:", filelist);
    fromDir(startPath, function (filename: string) {
        // log.info("filename:", filename);
        let splits = filename.split('\\');
        // log.info("splits:", splits);
        if (filename.indexOf(".xls") >= 0 && !splits[splits.length - 1].startsWith("~")) {
            // log.info("测试文件", filename);
            let stat = fs.lstatSync(filename);
            filelist.push({path: filename, mtime: stat.mtime, ctime: stat.ctime});
        }
    });
    // log.info("filelist:", JSON.stringify(filelist));
    // 根据修改时间排序
    filelist.sort(function (a: any, b: any) {
        return b.ctime - a.ctime;
    });
    // 获取最新的10个文件
    return filelist.slice(0, 5);
}

// 使用
// let latestFiles = getLatestFiles('/Users/lipeng/Desktop/赋隆快装数据库');
// console.log(latestFiles);

// const data = readExcelFile(latestFiles[0].path);
// console.log(data);

// 2024-01-11 12:12:12
// 01/08/06:08
function getTime(time: string, start_end_time: string) {
    if (time && start_end_time) {
        start_end_time = start_end_time.replace("：", ":");
        time = time.replace("：", ":");
        let strings = start_end_time.split("/");
        return `${time.substring(0, 4)}-${strings[0]}-${strings[1]} ${strings[2]}:00`;
    } else {
        return null
    }
}

class ExcelFulongCollector {
    init() {
        // let dataJson1: any = readExcelFile('/Users/lipeng/Desktop/赋隆快装数据库/2023年12月份报表/20231215赋隆曹妃甸西54节.xlsx');
        // let dataJson2: any = readExcelFile('/Users/lipeng/Desktop/赋隆快装数据库/2023年12月份报表/20231225赋隆曹妃甸西54节.xlsx');
        // console.log(dataJson1[5]);
        // console.log(dataJson2[5]);
        this.collection().catch((e) => {
            log.info(e);
        });
        setInterval(() => {
            this.collection().catch((e) => {
                log.info(e);
            });
        }, 1000 * 60 * 2)
    }

    async collection() {
        let files = getLatestFiles('//192.168.1.20/报表/新建文件夹');
        // let files = getLatestFiles('/Users/lipeng/Desktop/赋隆快装数据库');
        // log.info("files:", JSON.stringify(files));
        for (let i in files) {
            log.info("files[i].path:", JSON.stringify(files[i].path));
            let dataJson: any = readExcelFile(files[i].path);
            try {
                if (files[i].path.endsWith(".xls")) {
                    log.info("xls文件", files[i].path);
                    // xls 直接导出的文件
                    await this.xls(dataJson, files[i].path.split("\\").pop().split(".")[0]);
                    // } else if (dataJson[4].__EMPTY_8 && dataJson[4].__EMPTY_8 === '箱型') {
                    // 集装箱
                    // await this.jzx(dataJson, files[i].path.split("\\").pop().split(".")[0]);
                    // } else {
                    // 散装
                    // await this.sz(dataJson, files[i].path.split("\\").pop().split(".")[0]);
                }
            } catch (e) {
                log.info("dataJson:", dataJson);
                log.error(e);
            }
        }
    }

    private async xls(dataJson: any, name: string) {
        // log.info("xls dataJson:", JSON.stringify(dataJson));
        if (
            dataJson
            && dataJson[2]
            && dataJson[2].__EMPTY_1
        ) {
            log.info("dataJson[1]:", dataJson[1])
            log.info("dataJson[2]:", dataJson[2])
            log.info("dataJson[5]:", dataJson[5])
            const nodes: NodeCO[] = []
            let totalWeight = 0
            let totalMaxWeight = 0
            for (let j = 0; j < 200; j++) {
                if (
                    dataJson
                    && dataJson[j + begin]
                    && Number(dataJson[j + begin].__EMPTY_1)
                    && dataJson[j + begin].__EMPTY_2
                    && dataJson[j + begin].__EMPTY_3
                    // && Number(dataJson[j + begin].__EMPTY_4)
                    // && Number(dataJson[j + begin].__EMPTY_6)
                    // && Number(dataJson[j + begin].__EMPTY_8)
                ) {
                    // log.info("dataJson j :", j + begin, dataJson[j + begin])
                    totalWeight += Number(dataJson[j + begin].__EMPTY_6);
                    totalMaxWeight += Number(dataJson[j + begin].__EMPTY_4)
                    nodes.push({
                        centerDeviation: "", frontBackDiff: "",
                        diffWeight: dataJson[j + begin].__EMPTY_6 - dataJson[j + begin].__EMPTY_4,
                        code: dataJson[j + begin].__EMPTY_1 + "-" + dataJson[j + begin].__EMPTY_3,
                        lable: null,
                        maxNetWeight: dataJson[j + begin].__EMPTY_4,
                        no: dataJson[j + begin].__EMPTY_3,
                        sort: dataJson[j + begin].__EMPTY_1,
                        speed: null,
                        standardTareWeight: null,
                        time: null,
                        trainCode: "xls-" + dataJson[1].__EMPTY_2,
                        carType: dataJson[j + begin].__EMPTY_2,
                        weight: dataJson[j + begin].__EMPTY_6,
                        containerNumber1: null,
                        containerNumber2: null,
                        containerType1: null,
                        containerType2: null,
                        state: 'Done',
                        createTenantId: null,
                        createTenantName: null
                    })
                }
            }
            if (nodes.length === 0) {
                log.error("抓取行出错，请检查字段")
                return;
            }
            // log.info("nodes[0]:", nodes[0]);
            let train: TrainAllCO = {
                wagonType: nodes[0].no === nodes[1].no ? "Container" : "Gondola",
                firstNo: nodes[0].no,
                lastNo: nodes[nodes.length - 1].no,
                type: "excel",
                totalDiffWeight: totalWeight - totalMaxWeight,
                totalMaxWeight: totalMaxWeight,
                totalWeight: totalWeight,
                boxCount: null,
                code: "xls-" + dataJson[1].__EMPTY_2,
                deviceName: config.deviceName,
                direction: "Leave",
                name: name,
                no: dataJson[2].__EMPTY_2,
                nodes: nodes,
                platformId: config.platformId,
                platformName: config.platformName,
                productName: null,
                senderName: null,
                startTime: null,
                endTime: null,
                stationName: null,
                time: dataJson[1].__EMPTY_2,
                createTenantId: null,
                createTenantName: null,
                totalNode: nodes.length
            }
            // log.info("trainAll:", train);
            try {
                await sender.send("trainAll", train);
            } catch (e) {
                log.error("err dataJson:", dataJson);
            }
        }
    }
}

const excelFulongCollector = new ExcelFulongCollector();
export default excelFulongCollector;